package com.hx.vending.controller;

import com.hx.vending.annotation.*;
import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.*;
import com.hx.vending.service.*;
import com.hx.vending.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/11/27.
 */
@Controller
@RequestMapping("/userToken")
public class UserTokenController {

    // 获取logger实例
    protected static Logger logger = Logger.getLogger(UserTokenController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private ITokenService tokenService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IDataAuditService dataAuditService;

    //缓存对象
    @Autowired
    private RedisTemplate<String, List<RegionVo>> redisTemplate;

    /**
     * 登录
     * @param userPhone
     * @param userPassWord
     * @return user 0不是子账户 1是子账户
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Msg login(@RequestParam("userPhone") String userPhone,
                     @RequestParam("userPassWord") String userPassWord){
        if(ToolUtil.isEmpty(userPhone) || ToolUtil.isEmpty(userPassWord)){
            return Msg.fail().add("va_msg", "账号或密码不能为空");
        }
        User user = userService.selectByPrimary(userPhone);
        if (user.getUserSubsidiaryUse() == 0){
            return Msg.fail().add("va_msg","该账户不可用");
        }
        if(ToolUtil.isEmpty(user)){
            return Msg.fail().add("va_msg", "未找到对应的账户信息");
        }else if(!user.getUserPassWord().equals(MD5.string2MD5(userPassWord))){
            return Msg.fail().add("va_msg","密码错误");
        }
        // 生成一个token，保存用户登录状态
        String model = this.tokenService.createToken(user.getUserId());
        if(ToolUtil.isEmpty(user.getUserFather())){
            return Msg.success().add("token",model).add("user",0);
        }
        return Msg.success().add("token",model).add("user",1);
    }
    /*
    * 退出
    * */
    @RequestMapping(value = "/logout",method = RequestMethod.DELETE)
    @ResponseBody
    @Authorization
    public Msg logout(@PathVariable Integer userId) {
        tokenService.deleteToken(userId);
        return Msg.success();
    }

    /*
    * 用户注册
    * */
    @ResponseBody
    @RequestMapping(value="/register",method = RequestMethod.POST)
    public Msg register(String userName, String userPassWord, String userPhone,String secondaryPassword){
        User user = new User();
        try {
            user.setUserName(userName);
            user.setUserPassWord(userPassWord);
            user.setUserPhone(userPhone);
            user.setUserMoney(0.00);
            user.setUserSecondaryPassword(secondaryPassword);
            //user.setUserProfilePhoto("https://dongman168.oss-cn-shenzhen.aliyuncs.com/user/headIcon/default_head.png");
            User u = userService.findByUserPhone(userPhone);
            if (ToolUtil.isNotEmpty(u)) {
                return Msg.fail().add("va_msg", "该手机号已注册!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            return Msg.fail().add("va_msg", "请检查网络！");

        }
        // 默认设置库存警戒推送，默认警戒个数为 2个
        user.setUserStockNotice("2");
        user.setUserStoclNoticeNum(2);
        //用户注册时间
        user.setUserCreatTime(ToolUtil.currentTime());
        //四个推送，默认为关闭(2)
        user.setUserIncomePush("2");
        user.setUserOrderPush("2");
        user.setUserTxPush("2");
        user.setUserOfflinePush("2");
        user.setUserWithdrawproportion(0.8F);
        //企业微信注册
        int code = PushUtils.getInstance().createMember(userPhone, userName, userPhone);
        if (code == 0 || code == 60104) {
            user.setUserAccount(userPhone);
            userService.insertByPhone(user);
            return Msg.success().add("va_msg", "注册成功");
        } else {
            return Msg.fail().add("msg", "注册成功,但企业微信注册失败,错误码: " + code);
        }
    }
    /***
     * 根据手机号发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pushMessageByPhone", method = RequestMethod.POST)
    public Msg pushMessageByPhone(@RequestParam(value = "phone") String phone, @RequestParam(value = "condition") String condition) {
        return userService.pushMessageByPhone(phone, condition);
    }
    /***
     * 校验验证码是否正确
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verifyCode", method = RequestMethod.POST)
    public Msg verifyCode(@RequestParam(value = "code") String code, @RequestParam(value = "msgId") String msgId) {
        return userService.verifyCode(code, msgId);
    }
    /*
    * 忘记密码
    * */
    @RequestMapping(value = "/forget", method = RequestMethod.POST)
    @ResponseBody
    public Msg Forget(String userPhone, String userPassWord,Integer type) {
        // 查询用户手机号码和密码
        //logger.info("手机号传入" + userPhone + "密码" + userPassWord);
        if(type == 0){
            try {
                userService.updatePassword(userPhone, userPassWord);
            } catch (Exception e) {
                logger.error(e);
                return Msg.fail().add("va_msg", "密码修改失败");
            }
            return Msg.success().add("va_msg", "密码修改成功");
        }else if (type == 1){
            try {
                userService.updateSecondaryPassword(userPhone, userPassWord);
            } catch (Exception e) {
                logger.error(e);
                return Msg.fail().add("va_msg", "密码修改失败");
            }
            return Msg.success().add("va_msg", "密码修改成功");
        }
        return Msg.fail();
    }

    /**
     * 获取首页信息（礼品消耗数，礼品金额，线下投币数,线上投币数, 今日总收益， 在线支付， 广告收益， 现金收益）
     */
    @RequestMapping(value = "/getInfoByUserId", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg getInfoByUserId(@RequestBody Map<String,Object> paramMap, @CurrentUserId Integer userId, @CurrentFieldId Integer[] integers) {
        Map<String, Object> map = new HashMap<>();
        if(ToolUtil.isEmpty(paramMap.get("startTime")) || ToolUtil.isEmpty(paramMap.get("endTime"))){
            return Msg.fail().add("msg", "起始时间不能为空");
        }
        /*if(ToolUtil.isEmpty(paramMap.get("fieldList"))){
            return Msg.fail().add("msg", "参数值错误");
        }*/
        //开始时间
        String startTime = (String) paramMap.get("startTime");
        //结束时间
        String endTime = (String) paramMap.get("endTime");
        //场地id数组
        List<Integer> fieldList = (List<Integer>) paramMap.get("fieldList");
        if(fieldList.get(0) == 0 || ToolUtil.isEmpty(fieldList)){
            fieldList.clear();
            if(ToolUtil.isNotEmpty(integers)){
                fieldList = Arrays.asList(integers);
            }else {
                fieldList = null;
            }

        }
        Msg goodsMsg =  goodsService.getGoodsByEquipmentInfo(startTime,endTime,fieldList,userId);
        if (goodsMsg.getCode() != 200) {
            return goodsMsg;
        }
        Map<String,Object> goodsVOList = (Map<String,Object>) goodsMsg.getExtend().get("goodsVOList");
        //System.out.println(goodsVOList.get(0).getGoodsConsumePrice());
        //商品总消耗数
        map.put("goodsCount", goodsVOList.get("goodsCount"));
        //商品总金额
        map.put("goodsPriceCount", goodsVOList.get("goodsConsumePrice"));
        // 线下金额
        Msg underOrderMsg = this.userService.getUnderOrderTod(userId, fieldList, startTime, endTime);
        if (underOrderMsg.getCode() != 200) {

            return underOrderMsg;
        }
        Double mapList = Double.parseDouble(underOrderMsg.getExtend().get("va_msg").toString());


        map.put("underOrderCount",mapList);
        // 线上投币数
        Msg onlineOrderMsg = this.userService.getOnlineOrderTod(userId, fieldList, startTime, endTime);
        if (onlineOrderMsg.getCode() != 200) {

            return onlineOrderMsg;
        }
        Double sumOnlineOrderNumber =  Double.parseDouble(onlineOrderMsg.getExtend().get("sumOnlineOrderNumber").toString());

        Double earnings = userService.getEarningsToday(userId, fieldList, startTime, endTime);

        /*Double refundMoney = Double.parseDouble();*/

        //线上总金额
        map.put("sumOnlineOrderNumber", sumOnlineOrderNumber);

        //合计
        Double money = BigDecimalUtils.add(mapList,sumOnlineOrderNumber);
        Double allMoney = BigDecimalUtils.sub(money,earnings);
        map.put("allMoney", allMoney);

        return Msg.success().addObject(map);
    }

    /**
     * 统计商户近30天/半年收益记录
     */
    @ResponseBody
    @RequestMapping(value = "/statisticalGain", method = RequestMethod.GET)
    @Authorization
    @AnnotationField
    public Msg statisticalGain(@CurrentUserId Integer userId,@CurrentFieldId Integer[] integers, String condition) {
        return userService.statisticalGain(userId, integers, condition);
    }
    /*
    * 修改账号推送设置
    * */
    @ResponseBody
    @RequestMapping(value = "/updateUserPush",method = RequestMethod.POST)
    @Authorization
    public Msg updateUserPush(@CurrentUserId Integer userId,@CurrentAccountId Integer account,String userIncomePush,String userOrderPush,
                              String userTxPush,String userOfflinePush){
        User user = new User();
        if(account == 0){
            user.setUserId(userId);
        }else {
            user.setUserId(account);
        }

        User u = userService.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            u.setUserId(u.getUserId());
            u.setUserIncomePush(userIncomePush);
            u.setUserOrderPush(userOrderPush);
            u.setUserTxPush(userTxPush);
            u.setUserOfflinePush(userOfflinePush);
            int result = userService.updateByPrimaryKeySelective(u);
            if(result != 0){
                return Msg.success().add("va_msg", "设置成功");
            }else{
                return Msg.fail().add("va_msg", "设置失败");
            }
        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }

    /**
     * 修改库存通知数量
     * @return
     */
    @RequestMapping("/updateUserStock")
    @ResponseBody
    @Authorization
    public Msg updateUserStock(@CurrentUserId Integer userId,Integer userStockNum){
        User u = new User();
        u.setUserId(userId);
        u.setUserStoclNoticeNum(userStockNum);
        int i = userService.updateByPrimaryKeySelective(u);
        if(i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 查询该商家下的客服电话号和微信号
     */
    @ResponseBody
    @RequestMapping(value = "/getNumberByUserId",method = RequestMethod.GET)
    @Authorization
    public Msg getNumberByUserId(@CurrentUserId Integer userId){
        return userService.getNumberByUserId(userId);
    }

    /**
     * 更新代理商客服二维码，客服电话和客服微信
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateCustomService", method = RequestMethod.POST)
    @Authorization
    public Msg updateCustomService(String userServiceWechat,String userServiceWechatQr,@CurrentUserId Integer userId){
        User user = new User();
        user.setUserId(userId);
        user.setUserServiceWechat(userServiceWechat);
        user.setUserServiceWechatQr(userServiceWechatQr);
        Msg msg = userService.updateCustomService(user);
        return msg;
    }
    /*
    * 修改客服电话
    * */
    @ResponseBody
    @RequestMapping(value = "/updateUserServicePhone", method = RequestMethod.POST)
    @Authorization
    public Msg updateUserServicePhone(@CurrentUserId Integer userId,String userServicePhone){
        return userService.updateuserServicePhone(userId,userServicePhone);
    }
    /*
    * 修改商户名称
    * */
    @ResponseBody
    @RequestMapping(value = "/updateUserMerchantName", method = RequestMethod.POST)
    @Authorization
    public Msg updateUserMerchantName(@CurrentUserId Integer userId, String userMerchantName) {
        return userService.updateuserMerchantName(userId,userMerchantName);
    }

    /**
     * 验证旧密码
     *
     * @param userId
     * @param userPassWord
     * @param type 0登录 1二级
     * @return
     */
    @RequestMapping(value = "/validatePassword", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public Msg validatePassword(@CurrentUserId Integer userId, String userPassWord,Integer type){
        User user = new User();
        user.setUserId(userId);
        User u = userService.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            if(type == 0){
                if (u.getUserPassWord().equals(MD5.string2MD5(userPassWord))) {
                    return Msg.success().add("va_msg", "密码正确");
                } else {
                    return Msg.fail().add("va_msg", "密码错误");
                }
            }else if(type == 1){
                if(u.getUserSecondaryPassword().equals(MD5.string2MD5(userPassWord))){
                    return Msg.success().add("va_msg", "密码正确");
                }else{
                    return Msg.fail().add("va_msg", "密码错误");
                }
            }
        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
        return Msg.fail();
    }

    /**
     * 设置新密码
     * @param userId
     * @param userPassWord
     * @param type 0登录密码 1二级密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserPassword", method = RequestMethod.POST)
    @Authorization
    public Msg updateUserPassword(@CurrentUserId Integer userId, String userPassWord, Integer type) {
        User user = new User();
        user.setUserId(userId);
        User u = userService.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            if(type == 0){
                int result = userService.updatePassword(u.getUserPhone(),userPassWord);
                if(result != 0){
                    return Msg.success().add("va_msg", "设置成功");
                }else{
                    return Msg.fail().add("va_msg", "设置失败");
                }
            }else {
                int result = userService.updateSecondaryPassword(u.getUserPhone(),userPassWord);
                if(result != 0){
                    return Msg.success().add("va_msg", "设置成功");
                }else{
                    return Msg.fail().add("va_msg", "设置失败");
                }
            }

        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }
     /*
     * 忘记密码 重新设置密码
     */
    @RequestMapping(value = "/forgetPassWord", method = RequestMethod.POST)
    @ResponseBody
    public Msg forgetPassWord(String userPhone,String userPassWord){
        int i = userService.updatePassword(userPhone,userPassWord);
        if(i != 0){
            return Msg.success().add("va_msg", "密码修改成功");
        }else{
            return Msg.fail().add("va_msg", "密码修改失败");
        }
    }

    /*
    * 根据代理商id获取整个代理商对象信息
    * */
    @RequestMapping(value = "/getUserByUserId", method = RequestMethod.GET)
    @ResponseBody
    @Authorization
    public Msg getUserByUserId(@CurrentUserId Integer userId,@CurrentAccountId Integer account){
        return userService.getUserByUserId(userId,account);
    }

    /**
     * 上传头像
     *
     * @param userId
     * @param imgStr
     * @return
     */
    @RequestMapping("/saveUserProfilePhoto")
    @ResponseBody
    @Authorization
    public Msg saveThrowReplyPic(@CurrentUserId Integer userId,@CurrentAccountId Integer account, @RequestParam(value = "imgStr") String imgStr){
        User u = new User();
        if (account == 0){
            u.setUserId(userId);
        }else {
            u.setUserId(account);
        }
        User user = userService.selectByPrimaryKey(u);
        if(ToolUtil.isNotEmpty(user)) {
            //先删除原来的头像
            AliyunOSSClientUtil.deleteObject(user.getUserProfilePhoto());

            user.setUserPassWord(null);
            user.setUserProfilePhoto(imgStr);
            int result = userService.updateByPrimaryKeySelective(user);
            if (result != 0) {
                return Msg.success();
            } else {
                return Msg.fail();
            }
        }else {
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }

    /**
     * 库存通知推送
     * @param userId
     * @param userStockNotice
     * @return
     */
    @RequestMapping(value = "/updateUserStockNotice",method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public Msg updateuserStockNotice(@CurrentUserId Integer userId, String userStockNotice){
        User user = new User();
        user.setUserId(userId);
        User u = userService.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            u.setUserStockNotice(userStockNotice);
            int result = userService.updateByPrimaryKeySelective(u);
            if (result != 0) {
                return Msg.success().add("va_msg", "设置成功");
            } else {
                return Msg.fail().add("va_msg", "设置失败");
            }
        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }
    /**
     * 银行卡信息绑定
     *
     * @throws Exception
     * @throws SocketTimeoutException
     */
    @ResponseBody
    @RequestMapping(value = "/bindingBank", method = RequestMethod.POST)
    @Authorization
    public Msg selectByDiscountid7(@RequestBody Map<String,Object> map,@CurrentUserId Integer userId){
        //法人姓名
        String userLegalPersonName = map.get("userLegalPersonName").toString();
        //法人证件号
        String userLegalPersonIdCard = map.get("userLegalPersonIdCard").toString();
        //身份证正面
        String userLegalPersonIdPositive = map.get("userLegalPersonIdPositive").toString();
        //身份证反面
        String userLegalPersonIdOther = map.get("userLegalPersonIdOther").toString();
        User u = new User();
        u.setUserId(userId);
        User user = userService.selectByPrimaryKey(u);
        // 法人姓名
        user.setUserLegalPersonName(userLegalPersonName);
        // 身份证号
        user.setUserLegalPersonIdCard(userLegalPersonIdCard);
        //身份证正面
        user.setUserLegalPersonIdPositive(userLegalPersonIdPositive);
        //身份证反面
        user.setUserLegalPersonIdOther(userLegalPersonIdOther);
        //银行卡账号
        user.setUserBankAccountNo(map.get("userBankAccountNo").toString());
        //银行卡图片
        user.setUserBankCardImage(map.get("userBankCardImage").toString());
        //营业执照
        user.setUserBusinessLicense(map.get("userBusinessLicense").toString());
        //店铺照片
        user.setUserShopPicture(map.get("userShopPicture").toString());
        user.setUserWechatNumber(map.get("userWechatNumber").toString());
        user.setUserAlipayNumber(map.get("userAlipayNumber").toString());
        int i = userService.updateByPrimaryKeySelective(user);
        if(i > 0){
            // 插入或者更新审核表信息
        Msg msg = this.dataAuditService.insertDataAudit(userId);
        if (msg.getCode() != 200) {
            return msg;
        }
            return Msg.success().add("va_msg", "身份提交成功");
        }else{
            return Msg.fail().add("va_msg", "身份提交失败");
        }

    }

    /**
     * 根据用户id查询工商信息
     * @param userId
     * @return
     */
    @RequestMapping("/selectBindingBank")
    @ResponseBody
    @Authorization
    public Msg selectBindingBank(@CurrentUserId Integer userId){
        UserVO u = userService.selectBankByUserId(userId);
        if(ToolUtil.isNotEmpty(u)){
        DataAudit d = new DataAudit();
        d.setUserId(userId);
        List<DataAudit> dataAuditList = dataAuditService.selectByExample(d);
        if(dataAuditList.size() <= 0){
            u.setAuditState(0);
        }else {
            DataAudit dataAudit = dataAuditList.get(0);
            u.setAuditState(dataAudit.getAuditState());
            u.setAuditRemark(dataAudit.getAuditRemark());
        }
        return Msg.success().add("user",u);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 根据用户id查询工商信息(后台使用)
     * @param userId
     * @return
     */
    @RequestMapping("/selectUserBank")
    @ResponseBody
    public Msg selectUserBank( Integer userId){
        UserVO u = userService.selectBankByUserId(userId);
        if(ToolUtil.isNotEmpty(u)){
            DataAudit d = new DataAudit();
            d.setUserId(userId);
            List<DataAudit> dataAuditList = dataAuditService.selectByExample(d);
            if(dataAuditList.size() <= 0){
                u.setAuditState(0);
            }else {
                DataAudit dataAudit = dataAuditList.get(0);
                u.setAuditState(dataAudit.getAuditState());
                u.setAuditRemark(dataAudit.getAuditRemark());
            }
            return Msg.success().add("user",u);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 查询工商资料状态
     * @param userId
     * @return
     */
    @RequestMapping("/selectAuditState")
    @ResponseBody
    @Authorization
    public Msg selectAudit(@CurrentUserId Integer userId){
        DataAudit dataAudit = new DataAudit();
        dataAudit.setUserId(userId);
        List<DataAudit> dataAuditList = dataAuditService.selectByExample(dataAudit);
        Map<String,Object> map = new HashMap<>();
        String i = "";
        if(dataAuditList.size() <= 0){
            map.put("auditState","0");
        }else {
            DataAudit dataAudit1 = dataAuditList.get(0);
            map.put("auditState",dataAudit1.getAuditState().toString());
            map.put("auditRemark",dataAudit1.getAuditRemark());
        }
        return Msg.success().add("dataAudit",map);
    }

    /**
     * 审核工商资料
     * @param dataAudit
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkAudit")
    public Msg checkAudit(@RequestBody DataAudit dataAudit){
        dataAudit.setAuditTime(DateUtil.getTime());
        int i = dataAuditService.updateDataAuit(dataAudit);
        if(i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }


    /*
    * 区域代码
    * */
    @RequestMapping("/area")
    @ResponseBody
    public Msg getRegion(){
        //获取缓存数据-
        List<RegionVo> regionsLevelOne = new ArrayList<>();
        if(isExistListInRedis("region")){
            List<List<RegionVo>> list = redisTemplate.boundListOps("region").range(0,-1);
            regionsLevelOne = list.get(0);
        }else{
            regionsLevelOne = userService.selectRegionOne();
            for(int i = 0;i < regionsLevelOne.size();i++){
                List<RegionDetailVo> regionsLevelTwo = userService.selectRegionVoByPid(regionsLevelOne.get(i).getRegionId());
                for(int j = 0;j < regionsLevelTwo.size();j++){
                    List<Region> regionsLevelThree = userService.selectRegionByPid(regionsLevelTwo.get(j).getRegionId());
                    regionsLevelTwo.get(j).setRegionList(regionsLevelThree);
                }
                regionsLevelOne.get(i).setRegionList(regionsLevelTwo);
            }

            redisTemplate.boundListOps("region").leftPush(regionsLevelOne);
            System.out.println("=================存入缓存");
            redisTemplate.boundListOps("region").expire(300, TimeUnit.DAYS);// 设置时间
        }
        return Msg.success().add("regionList",regionsLevelOne);
    }
    // 判断列表类型的key值是否存在
    private boolean isExistListInRedis(String key) {
        return redisTemplate.boundListOps(key).size() == 0 ? false : true;
    }

    /**
     *根据设备id返回商户客服信息
     * @param equipmentId
     * @return
     */
    @RequestMapping("/selectUserService")
    @ResponseBody
    public Msg selectUserService(String equipmentId){
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        Equipment equipment = equipmentService.selectByPrimary(e);
        if(ToolUtil.isNotEmpty(equipment)){
            UserService user = userService.selectUserServiceById(equipment.getEquipmentUserId());
            user.setEquipmentId(equipmentId);
            return Msg.success().add("userService",user);
        }
        return Msg.fail();
    }

    /**
     * 工商资料信息列表
     */
    @RequestMapping("/selectUserBankList")
    @ResponseBody
    public Msg selectUserBankList(String userName,String state,String startTime,String endTime,
                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        Integer num = dataAuditService.selectCount(userName,state,startTime,endTime);
        //分页页数 从pageNum开始，查十条
        Integer pageStart = (pageNum - 1) * 10;
        List<UserAudit> map = userService.selectUserBankList(userName,state,startTime,endTime,pageStart);
        return Msg.success().add("userBankList",map).add("count",num);
    }

    /**
     * 获取所有商户
     * @param userName
     * @param userPhone
     * @param pageNum
     * @return
     */
    @RequestMapping("/selectAllUser")
    @ResponseBody
    public Msg selectAllUser(String userName,String userPhone,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        Integer num = userService.selectUserNum(userName,userPhone);
        Map<String,Object> map = new HashMap<>();
        if(ToolUtil.isNotEmpty(userName)){
            map.put("userName",userName);
        }
        if(ToolUtil.isNotEmpty(userPhone)){
            map.put("userPhone",userPhone);
        }
        Integer pageStart = (pageNum - 1) * 10;
        map.put("pageStart",pageStart);
        List<User> userList = userService.selectUserBack(map);
        return Msg.success().add("userList",userList).add("num",num);

    }

    /**
     * 删除用户
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteUser/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteUser(@PathVariable("ids") String ids)throws Exception{
        Boolean b = false;
        //批量删除
        if(ids.contains("-")){
            String[] strs = ids.split("-");
            List<Integer> stringList = new ArrayList<>(strs.length);
            String[] strs1= new String[strs.length];
            for(int i = 0;i <strs.length;i++){
                int j = equipmentService.updateEquipmentByUserId(Integer.parseInt(strs[i]));

                User user = userService.selectUserById(Integer.parseInt(strs[i]));
                stringList.add(user.getUserId());
                strs1[i] = user.getUserAccount();
            }
            b = PushUtils.getInstance().deleteMember(strs1);
            if(b){
                userService.deleteBatchByList(stringList);
            }
        }else{
            int j = equipmentService.updateEquipmentByUserId(Integer.parseInt(ids));
                User user = userService.selectUserById(Integer.parseInt(ids));
           /* List<String> list = new ArrayList<>();
            list.add(user.getUserAccount());*/
                b = PushUtils.getInstance().deleteMember1(user.getUserAccount());
                if(b){
                    userService.deleteByPrimaryKey(Integer.parseInt(ids));
                }
        }
        if(b){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 添加商户提现信息
     * @param user
     * @return
     */
    @RequestMapping("/updateUserDrawCashMessage")
    @ResponseBody
    @Authorization
    public Msg updateUserDrawCashMessage(@CurrentUserId Integer userId, User user) {

        return this.userService.updateUserDrawCashMessage(userId, user);
    }


    /**
     * 验证二级密码
     * @param userId
     * @param secondaryPassword
     * @return
     */
    @RequestMapping("/selectVerificationSecondaryPassword")
    @ResponseBody
    @Authorization
    public Msg selectVerificationSecondaryPassword(@CurrentUserId Integer userId, String secondaryPassword) {

        return this.userService.selectVerificationSecondaryPassword(userId, secondaryPassword);
    }


    /**
     * 查询商户提现信息
     * @param userId
     * @return
     */
    @RequestMapping("/selectUserWithdrawProportion")
    @ResponseBody
    @Authorization
    public Msg selectUserWithdrawProportion(@CurrentUserId Integer userId) {

        return this.userService.selectUserWithdrawProportion(userId);
    }
    /**
     * 修改商户提现比例
     * @param userId
     * @return
     */
    @RequestMapping("/updateUserWithdrawProportion")
    @ResponseBody
    @Authorization
    public Msg updateUserWithdrawProportion(@CurrentUserId Integer userId, Float withdrawProportion) {

        return this.userService.updateUserWithdrawProportion(userId, withdrawProportion);
    }

    /**
     * 添加子账户
     * @param userId 商家id
     * @param userName
     * @param userPassWord
     * @param userPhone
     * @param roleId 岗位
     * @param fieldId 场地
     * @return
     */
    @RequestMapping("/addSubAccount")
    @ResponseBody
    @Authorization
    public Msg addSubAccount(@CurrentUserId Integer userId,String userName, String userPassWord, String userPhone,Integer roleId,String fieldId){
        User u = userService.findByUserPhone(userPhone);
        if (ToolUtil.isNotEmpty(u)){
            return Msg.fail().add("msg","该手机号已注册");
        }
        User user = new User();
        user.setUserCreatTime(DateUtil.getTime());
        user.setUserName(userName);
        user.setUserPassWord(userPassWord);
        user.setUserPhone(userPhone);
        user.setUserFather(userId.toString());
        user.setUserRole(roleId.toString());
        user.setUserFieldId(fieldId);
        user.setUserOfflinePush("1");
        user.setUserSubsidiaryUse(1);
        user.setUserMoney(0.00);
        int i = userService.insertByPhone(user);
        if (i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 子账户列表
     * @param userId
     * @return
     */
    @RequestMapping("/selectSubAccount")
    @ResponseBody
    @Authorization
    public Msg selectSubAccount(@CurrentUserId Integer userId ,String userName){
        return userService.selectSubAccount(userId,userName);
    }

    /**
     *子账号详情
     * @param account
     * @return
     */
    @RequestMapping("/selectSubAccountDetails")
    @ResponseBody
    public Msg selectSubAccountDetails(Integer account){

        return userService.selectSubAccountDetails(account);
    }

    /**
     * 删除子账号
     * @param account
     * @return
     */
    @RequestMapping(value = "/deleteSubAccount/{account}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteSubAccount(@PathVariable Integer account){
        int i = userService.deleteByPrimaryKey(account);
        if (i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 编辑子账号
     * @return
     */
    @ResponseBody
    @RequestMapping("/editSubAccount")
    public Msg editSubAccount(Integer userId,String userName, String userPassWord, String userPhone,String roleId,String fieldId){
        int i = userService.updateSubAccount(userId,userName,userPassWord,userPhone,roleId,fieldId);
        if(i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 账号启用禁用
     * @param account 账号id
     * @param subsidiaryUse 子账号是否可用(0.否 1.是)
     * @return
     */
    @ResponseBody
    @RequestMapping("/editSubAccountUse")
    public Msg editSubAccountUse(Integer account,Integer subsidiaryUse){
        return userService.editSubAccountUse(account,subsidiaryUse);
    }


    /**
     * 查询登陆账号的权限
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectUserOperation")
    @Authorization
    public Msg selectUserOperation(@CurrentAccountId Integer userId) {
        return this.userService.selectUserOperation(userId);
    }

}
